package com.mao.server.interceptors;

import cn.hutool.core.util.StrUtil;
import com.mao.server.annotation.AuthAccess;
import com.mao.server.constant.Constants;
import com.mao.server.constant.JwtClaimsConstant;
import com.mao.server.constant.ResultConstant;
import com.mao.server.exception.ServiceException;
import com.mao.server.properties.JwtProperties;
import com.mao.server.utils.BaseContext;
import com.mao.server.utils.JwtUtil;
import com.mao.server.utils.TokenUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // @AuthAccess 放行
        if (handler instanceof HandlerMethod) {
            AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
            if (annotation != null) {
                return true;
            }
        }

        String token = "";
        String authHeader = request.getHeader(Constants.AUTH_HEADER);

        if (authHeader != null && authHeader.startsWith(Constants.TOKEN_PREFIX)) {
            token = authHeader.substring(Constants.TOKEN_PREFIX.length());
        } else if(StrUtil.isBlank(token)){
            token = request.getParameter("token");
        }else{
            throw new ServiceException(Constants.TOKEN_NULL_OR_EXPIRED);
        }


        try {
            TokenUtil.verifyToken(token);
            return true;
        } catch (Exception e) {
            throw new ServiceException(ResultConstant.AUTH_ERROR, Constants.TOKEN_VERIFY_ERROR + Constants.PLEASE_LOGIN);
        }
    }
}
